package com.barry;

import com.barry.bean.ColumnProperty;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.TreeMap;

/**
 * 类功能描述：//TODO
 *
 * @author WangXueXing create at 18-10-30 下午2:06
 * @version 1.0.0
 */
public class ObjValueByAnnotation {

    /**
     * 根据注解获取值列表
     * @param valList
     * @param clazz
     * @return
     * @throws IllegalAccessException
     */
    public static List<String> getValueWithHead(List<Object> valList, Class<?> clazz) throws IllegalAccessException {
        Field[] allFields = clazz.getDeclaredFields();// 得到所有定义字段
        List<Field> fields = new ArrayList<>();
        // 得到所有field并存放到一个list中.
        for (Field field : allFields) {
            if (field.isAnnotationPresent(ColumnProperty.class)) {
                fields.add(field);
            }
        }

        TreeMap<Integer, Field> columnPropertyMap = new TreeMap<>();
        for(Field field : fields) {
            field.setAccessible(true);// 设置实体类私有属性可访问
            ColumnProperty attr = field.getAnnotation(ColumnProperty.class);
            columnPropertyMap.put(attr.index(), field);
        }
        Collection<Field>  sortedFields = columnPropertyMap.values();

        List<String> dataList = new ArrayList<>();
        int i = 0;
        for(Object val : valList){
            if(i == 0){
                StringBuilder sb = new StringBuilder(125);
                int j = 0;
                for(Field field : sortedFields){
                    field.setAccessible(true);// 设置实体类私有属性可访问
                    ColumnProperty attr = field.getAnnotation(ColumnProperty.class);
                    if(j==0){
                        sb.append(attr.name());
                    } else {
                        sb.append(",");
                        sb.append(attr.name());
                    }
                    j++;
                }
                dataList.add(sb.toString());
            }
            i++;

            StringBuilder sb = new StringBuilder(125);
            int j = 0;
            for(Field field : sortedFields){
                field.setAccessible(true);// 设置实体类私有属性可访问
                if(j==0){
                    sb.append(field.get(val).toString());
                } else {
                    sb.append(",");
                    sb.append(field.get(val).toString());
                }
                j++;
            }
            dataList.add(sb.toString());
        }
        return dataList;
    }
}
